package com.iot.inclinometer.util;

import android.content.Context;

import com.iot.inclinometer.pojo.BaseInfo;
import com.iot.inclinometer.pojo.CorrectDataInfo;
import com.iot.inclinometer.pojo.DataInfo;
import com.iot.inclinometer.pojo.ObserveInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 导出更多数据（导出包含角度的数据）
 * 
 * @author ZSL
 * 
 */
public class JXLCreateMore implements Runnable {

	private String _file=null;
	private BaseInfo baseInfo = null;
	private ObserveInfo observeInfo = null;
	private Context context = null;
	private List<DataInfo> dataInfos0= new ArrayList<DataInfo>();
	private List<DataInfo> dataInfos180 = new ArrayList<DataInfo>();
	private List<CorrectDataInfo> correctDataInfos = new ArrayList<CorrectDataInfo>();
	private FileOutputStream fos = null;
	private WritableWorkbook wwb = null;
	private File fileDir  = null;
	private String filePath = null;
	private File targetFile = null;
	/*private String[] baseInfoTitles = { "工程名称", "工点名称", "钻孔编号", "孔深", "里程桩号",
			"位置描述", "X坐标", "Y坐标", "观测人员", "天气", "时间", "测量间距(cm)", "方位角"};*/
	private String[] baseInfoTitles = { "工程名称", "工点名称", "钻孔编号", "孔深", "里程桩号",
			"位置描述", "X坐标", "Y坐标", "观测人员","时间", "测量间距(cm)"};

	private String[] measureDataTitles= { "孔深（m）", "A0θxoz（°）","B0θyoz（°）","A180θxoz（°）","B180θyoz（°）",
			"θA方向","θB方向","主滑滑动位移（mm）","非主滑滑动位移（mm）","总滑动位移（mm）"};
	
	public JXLCreateMore(String file,BaseInfo baseInfo, ObserveInfo observeInfo,
			List<DataInfo> dataInfos0,List<DataInfo> dataInfos180,List<CorrectDataInfo> correctDataInfos,Context context) {
		this._file=file;
		this.baseInfo = baseInfo;
		this.observeInfo = observeInfo;
		this.dataInfos0= dataInfos0;
		this.dataInfos180= dataInfos180;
		this.correctDataInfos=correctDataInfos;
		this.context = context;
	}

	/*
	 * Excel文件生成过程 1.基本信息肯定有，观察信息至少2个，数据可能无 2.判断数据是否存在，如果不存在，文件命名时加上 NULL 作为命名后缀
	 * 3.每个测量数据保存为一份文件
	 * 
	 * 命名规则 --项目名称（文件夹） ----工点名称（文件夹）
	 * ------01-大山洞滑坡ZK08二140305.xls（文件）————PS：有效次数+工点名称+钻孔编号+监测次数+时间.xls
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		try {
			// 准备设置excel工作表的标题     // 输出的excel的路径
			fileDir = new File(_file+ File.separator + baseInfo.getProjectName()
					+ File.separator + baseInfo.getItemName());
					//通常 File f = new File("F:\\java\\rose"); 参数为字符串格式的路径
					//定义目录，例如_file为/sdcard/baofeng，它整体就是一个字符串，实际上如果把它表示出来，
					//应该是”//sdcard//baofeng”，所以后面还要加File.separator+ProjectName+File.separator+ItemName
					//构成一个完整的路径
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}
			
			String[] time=observeInfo.getTime().split("-");
			String year=time[0];
			String month=time[1];
			String[] dayAndTime=time[2].split(" ");
			String day=dayAndTime[0];
			String[] hourAndMinute=dayAndTime[1].split(":");
			String hour=hourAndMinute[0];
			String minute=hourAndMinute[1];
			
			if (correctDataInfos.size() < 1) {
				filePath = baseInfo.getDrillNum()+"-"+observeInfo.getCount()
						+ "-"+year+month+day+ "-"+hour+ "-"+minute+ "（空）.xls"; // 定义导出文件
			} else {
				filePath = baseInfo.getDrillNum()+"-"+observeInfo.getCount()
						+ "-"+year+month+day+ "-"+hour+ "-"+minute+ ".xls"; // 定义导出文件
			}

			if (new File(fileDir, filePath).exists()) { // 如果这个文件存在，那么暂时不做处理

			} else {
				targetFile = new File(fileDir, filePath);
				// 创建Excel工作薄
				
				// 新建立一个jxl文件,即在SDcard盘下生成test.xls
				fos = new FileOutputStream(targetFile);
				wwb = Workbook.createWorkbook(fos);
				// 添加第一个工作表并设置第一个Sheet的名字
				WritableSheet sheet = wwb.createSheet("测斜仪数据", 0);
                // System.out.println("到这一步啦");
				// 添加基本信息
				this.createBaseInfo(sheet, baseInfoTitles, baseInfo,
						observeInfo);

				//创建测量数据
				Label label;
				for (int i = 0; i < measureDataTitles.length; i++) {
					// Label(x,y,z)其中x代表单元格的第x+1列，第y+1行, 单元格的内容是z
					// 在Label对象的子对象中指明单元格的位置和内容
					label = new Label(i, 4, measureDataTitles[i]);
					// 将定义好的单元格添加到工作表中
					sheet.addCell(label);
				}	
				
				int length = correctDataInfos.size();
				double[] depths = new double[length];
				//观测数据
				double[] thetaX0s=new double[length];
				double[] thetaY0s=new double[length];
				double[] thetaX180s=new double[length];
				double[] thetaY180s=new double[length];
				//修正数据
				double[] cthetaXs=new double[length];
				double[] cthetaYs=new double[length];
				double[] clxs = new double[length];
				double[] clys = new double[length];
				double[] cerrors = new double[length];
				
				int i = 0;
				for (DataInfo d : dataInfos0) {
					depths[i] = Double.parseDouble(d.getDepth());
					thetaX0s[i] = Double.parseDouble(d.getThetaX())*180/3.1415926;
					thetaY0s[i] = Double.parseDouble(d.getThetaY())*180/3.1415926;
					i++;
				}	
				i = 0;
				for (DataInfo d : dataInfos180) {
					thetaX180s[i] = Double.parseDouble(d.getThetaX())*180/3.1415926;
					thetaY180s[i] = Double.parseDouble(d.getThetaY())*180/3.1415926;
					i++;
				}
				i=0;
				for (CorrectDataInfo d : correctDataInfos) {
					cthetaXs[i] = Double.parseDouble(d.getThetaX())*180/3.1415926;
					cthetaYs[i] = Double.parseDouble(d.getThetaY())*180/3.1415926;
					clxs[i] = Double.parseDouble(d.getLx());
					clys[i] = Double.parseDouble(d.getLy());
					cerrors[i] = Double.parseDouble(d.getError());
					i++;
				}	
				
				
				int lineNum = 5;
				for (int x = 0; x < length; x++) {
					// 深度
					jxl.write.Number depth = new jxl.write.Number(0, lineNum,depths[x]);
					sheet.addCell(depth);
					// A0
					jxl.write.Number thetaX0 = new jxl.write.Number(1, lineNum,thetaX0s[x]);
					sheet.addCell(thetaX0);
					jxl.write.Number thetaY0 = new jxl.write.Number(2, lineNum,thetaY0s[x]);
					sheet.addCell(thetaY0);
					// A180
					jxl.write.Number thetaX180 = new jxl.write.Number(3, lineNum,thetaX180s[x]);
					sheet.addCell(thetaX180);
					jxl.write.Number thetaY180 = new jxl.write.Number(4, lineNum,thetaY180s[x]);
					sheet.addCell(thetaY180);
					//修正数据
					jxl.write.Number cthetaX = new jxl.write.Number(5, lineNum,cthetaXs[x]);
					sheet.addCell(cthetaX);
					jxl.write.Number cthetaY = new jxl.write.Number(6, lineNum,cthetaYs[x]);
					sheet.addCell(cthetaY);
					jxl.write.Number clx = new jxl.write.Number(7, lineNum,clxs[x]);
					sheet.addCell(clx);
					jxl.write.Number cly = new jxl.write.Number(8, lineNum,clys[x]);
					sheet.addCell(cly);
					jxl.write.Number cerror = new jxl.write.Number(9, lineNum,cerrors[x]);
					sheet.addCell(cerror);		
					lineNum++;
				}	
				
				
				// 写入数据
				wwb.write();
				// 关闭文件
				wwb.close();
			}

		} catch (Exception e) {
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}			
		}
	}

	/**
	 * 对于本表中数据的说明，来自哪个工程，哪个工点，等等，说明信息
	 * 
	 * @param sheet
	 * @param baseInfoTitles
	 * @param info
	 * @throws Exception
	 */
	private void createBaseInfo(WritableSheet sheet, String[] baseInfoTitles,
			BaseInfo info, ObserveInfo observeInfo) throws Exception {
		Label label;
		for (int i = 0; i < baseInfoTitles.length; i++) {
			// Label(x,y,z)其中x代表单元格的第x+1列，第y+1行, 单元格的内容是y
			// 在Label对象的子对象中指明单元格的位置和内容
			label = new Label(i, 0, baseInfoTitles[i]);
			// 将定义好的单元格添加到工作表中
			sheet.addCell(label);
		}
		// Log.i("INFO", "创了EXCEL表格！");
		// 填充项目名字
		label = new Label(0, 1, info.getProjectName());
		sheet.addCell(label);
		// 填充工程名字
		label = new Label(1, 1, info.getItemName());
		sheet.addCell(label);
		// 填充钻孔编号
		label = new Label(2, 1, info.getDrillNum());
		sheet.addCell(label);
		// 填充深度
		label = new Label(3, 1, info.getDepth());
		sheet.addCell(label);
		// 里程桩号
		label = new Label(4, 1, info.getMark1() + info.getMark2() + "(km)"
				+ info.getMark3() + info.getMark4() + "(km)");
		sheet.addCell(label);
		// 位置描述
		label = new Label(5, 1, info.getLoc());
		sheet.addCell(label);
		/*
		// X坐标
		jxl.write.Number x = new jxl.write.Number(6, 1, Float.parseFloat(info.getX()));
														//注意X，Y不能为空，否则会报错
		sheet.addCell(x);
		// Y坐标
		jxl.write.Number y = new jxl.write.Number(7, 1, Float.parseFloat(info.getY()));
														//注意X，Y可以是小数，所以转浮点型，而不是整型，否则会报错
		sheet.addCell(y);
		*/
		// X坐标
		label = new Label(6, 1, info.getX());
		sheet.addCell(label);
		// Y坐标
		label = new Label(7, 1, info.getY());
		sheet.addCell(label);
		// 观察人员
		label = new Label(8, 1, observeInfo.getObserver());
		sheet.addCell(label);
		// 日期
		label = new Label(9, 1, observeInfo.getTime());
		sheet.addCell(label);
		// 间距
		label = new Label(10, 1, observeInfo.getInterval());
		sheet.addCell(label);
		
	}

}
